package cn.net.wenzhixin.cordova;


import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;

import com.ibm.mqtt.IMqttClient;
import com.moyue.active.LocationSourceActivity;
import com.moyue.active.MainActivity;
import com.moyue.active.R;
import com.services.PushActivity;
import com.services.PushService;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONArray;
import org.json.JSONException;



public class ExtraInfo extends CordovaPlugin {
    MqttAndroidClient mqttClient;
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
            throws JSONException {
        Activity activity = this.cordova.getActivity();

        System.out.print(args.get(0));
        System.out.print(args.get(1));
        if (action.equals("getExtra1")) {
            Intent i = activity.getIntent();
            if (i.hasExtra(Intent.EXTRA_TEXT)) {
                callbackContext.success(i.getStringExtra(Intent.EXTRA_TEXT));
            } else {
                callbackContext.error("asfdasdf");
            }
            return true;
        }

        if(action.equals("getExtra2")){

            this.onOverrideUrlLoading("file:///android_asset/www/chart1.html#chat");
           Activity activity1 = new PushActivity();
            Intent i =new Intent(activity,activity1.getClass());
          //  Intent ii = new Intent(activity1, PushService.class);
         //   cordova.getActivity().startService(ii);
           //
           //
           cordova.getActivity().startActivityForResult(i, 200);
            callbackContext.success("??????");

        }
        if(action.equals("getExtra")){
            this.cordova.getActivity();
            Intent i =new Intent();
            i.setClass(this.cordova.getActivity(), LocationSourceActivity.class);
            this.cordova.getActivity().startActivity(i);
           // String serverURI = "tcp://192.168.31.182";
            String serverURI = "tcp://"+args.get(1);



            conPhaoMqtt( serverURI,args.get(0).toString(),callbackContext);
            callbackContext.success("???????????????"+args.getString(0));
        }
        //????????????
        if(action.equals("publish")){
            if(mqttClient!=null){
                MqttMessage mm = new MqttMessage();

                mm.setPayload("nizainali".getBytes());

                try {

                    mqttClient.publish("864587025867988_898600",mm);

                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        }
        if(action.equals("getMap")){
            this.cordova.getActivity();
            Intent i =new Intent();
            i.setClass(this.cordova.getActivity(), LocationSourceActivity.class);


            this.cordova.getActivity().startActivityForResult(i,1);


        }

        return false;
    }


    public void conPhaoMqtt(String serverURI, final String o,final CallbackContext callbackContext) {
       //String serverURI = "tcp://192.168.31.182";

        mqttClient = new MqttAndroidClient( this.cordova.getActivity(), serverURI, o);



        mqttClient.setCallback(new MqttCallback() {
            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {


               cordova.getActivity().runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                       webView.postMessage("splashscreen", "show");


                   }
               });
               // webView.sendJavascript("jumpToChat()");//????????????

                //onOverrideUrlLoading("file:///android_asset/www/chart1.html#chat");
                showNotification(message.toString());
                //Toast.makeText(this.cordova.getActivity(), message.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void connectionLost(Throwable cause) {
                cause.printStackTrace();
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
            }
        });

        try {

            mqttClient.connect(null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken iMqttToken) {
                    try {

                       // mqttClient.subscribe("864587025867988_898600", 0);
                        mqttClient.subscribe(o,1);


                    } catch (MqttException e) {e.printStackTrace();}
                }

                @Override
                public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
                    throwable.printStackTrace();
                }
            });

        }catch (MqttException e){}


    }

    // Display the topbar notification
    private void showNotification(String text) {
        NotificationManager manager = (NotificationManager) this.cordova.getActivity()
                .getSystemService(
                        Context.NOTIFICATION_SERVICE);
        final String[] split = text.split("&");
        String toName = split[0];
        Notification notification = new Notification(R.drawable.icon, split[1],
                System.currentTimeMillis());

        Intent intent =  this.cordova.getActivity().getIntent();
        Intent clone = (Intent)intent.clone();//??????intent???????????????????????????????????????
        clone.putExtra("chat", "chat");
        clone.putExtra("toName",toName);
        Bundle bundle = new Bundle();
        bundle.putString("chat1", "chat");
        clone.putExtras(bundle);
        notification.setLatestEventInfo(this.cordova.getActivity(), "system",
                split[1], PendingIntent.getActivity(this.cordova.getActivity(),
                        Intent.FLAG_ACTIVITY_NEW_TASK |
                                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED, clone, 0));

        manager.notify(1, notification);




    }
}